package com.example.okhp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eclipsesource.v8.V8;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.StringDef;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class sixListActivity extends Activity {
	EditText edusrname;
	EditText edpassword;
	EditText edcode;
	ImageView imvcode;
	Button btnlog;
	Handler handler;
	OkHttpClient httpClient;
	String mainurl = "http://42.247.3.125/jsxsd";
	String codeurl = "http://42.247.3.125/jsxsd/verifycode.servlet";
	String postlogourl = "http://42.247.3.125/jsxsd/xk/LoginToXk";
	String cjcxstrString = "http://42.247.3.125/jsxsd/kscj/cjcx_query?";
	String cjliststr = "http://42.247.3.125/jsxsd/kscj/cjcx_list";
	public static ArrayList<ScoreMode> mylist = new ArrayList<ScoreMode>();

	public static String[] bainhao;
	public static String[] mingchen;
	public static String[] chengji;
	private HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();

	public void datainit() {
		for (int i = 0; i < mylist.size(); i++) {
			mylist.add(new ScoreMode(bainhao[i], mingchen[i], chengji[i]));
		}

	}

	public void geturlandCode() {
		// 1url 2.code cookie
		Request request = new Request.Builder().url(mainurl).build();// 初始化request 拿到请求对象
		Log.e("first send", "xxx");
		httpClient.newCall(request).enqueue(new Callback() { // callback结果的回调call接口，提供成功和失败的两个回调方法。
			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				Log.e("first content", "xxx");
				httpClient = new OkHttpClient.Builder().cookieJar(// 拿到client对象并带cookie
						new CookieJar() {
							@Override
							public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
								// TODO Auto-generated method stub
								cookieStore.put(httpUrl.host(), list);
							}
							@Override
							public List<Cookie> loadForRequest(HttpUrl httpUrl) {// httpUr.host()实际上是主机地址42.247.3.125
								// TODO Auto-generated method stub
								List<Cookie> cookies = cookieStore.get(httpUrl.host());
								Log.e("httpurl.host()", httpUrl.host());
								return cookies != null ? cookies : new ArrayList<Cookie>();
							}
						}).build();
				Request request2 = new Request.Builder().url(codeurl).build();// 请求验证码
				Log.e("second send", "xxxx");
				Response response2 = httpClient.newCall(request2).execute();
				// Log.e("second==",response2.toString());
				byte[] picbytes = response2.body().bytes();
				Log.e("bate", "" + picbytes.length);
				Message msg = handler.obtainMessage();
				msg.what = 1;
				msg.obj = picbytes;
				handler.sendMessage(msg);
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void onpostpwd() {
		String encodestr = null;
		InputStream is = null;
		try {
			is = getAssets().open("encode.js");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);// 用stringbulider来存储从输入流中读取到的数据
			}

			V8 runtime = V8.createV8Runtime();
			final String encodename = runtime
					.executeStringScript(sb.toString() + "encodeInp('" + edusrname.getText().toString() + "');\n");
			final String encodepwd = runtime
					.executeStringScript(sb.toString() + "encodeInp('" + edpassword.getText().toString() + "');\n");
			encodestr = encodename + "%%%" + encodepwd;
			runtime.release();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String code = edcode.getText().toString(); // 验证码
		//String encoded = "MTcxMDUwOTAxOQ==%%%Z3VvdG9uZzE5OTExNA==";

		FormBody.Builder builder = new FormBody.Builder();
		builder.add("encoded", encodestr); // 学号和密码
		builder.add("RANDOMCODE", code);
		FormBody formBody = builder.build();

		Request request = new Request.Builder().post(formBody).url(postlogourl).build();
		Log.e("thrid send", "xxxx" + "--------" + formBody + "-----------" + request);
		httpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {

			@Override
			public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
				// TODO Auto-generated method stub
				cookieStore.put(httpUrl.host(), list);
			}

			@Override
			public List<Cookie> loadForRequest(HttpUrl httpUrl) {
				// TODO Auto-generated method stub
				List<Cookie> cookies = cookieStore.get(httpUrl.host());
				// for (int i = 0; i < cookieStore .size(); i++) {
				// Log.e("cookieStore ", cookieStore .get(i).toString());
				// }
				return cookies != null ? cookies : new ArrayList<Cookie>();
			}
		}).build();
		httpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Call arg0, Response response) throws IOException {
				// TODO Auto-generated method stub
				String postresponceString = response.body().string().toString();
				// Log.e("responce==", postresponceString);
				int pos = postresponceString.indexOf("学生个人中心", 0);

				if (pos == -1) {
					// 重新加载验证码
					// System.out.println("验证码错误，已重新加载！");
					Request request_2 = new Request.Builder().url(codeurl).build();
					Response response2 = httpClient.newCall(request_2).execute();
					byte[] picbytes = response2.body().bytes();
					Log.e("bate_2", "" + picbytes.length);
					Message msg = handler.obtainMessage();
					msg.what = 3;
					msg.obj = picbytes;
					handler.sendMessage(msg);

				} else {
					System.out.println("nice");
					Message msg = handler.obtainMessage();
					msg.what = 2;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void getcj() {
		if (1 == 1) {
			Log.e("课表", "xxx");
			httpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
				@Override
				public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
					// TODO Auto-generated method stub
					cookieStore.put(httpUrl.host(), list);
				}
				@Override
				public List<Cookie> loadForRequest(HttpUrl httpUrl) {
					// TODO Auto-generated method stub
					List<Cookie> cookies = cookieStore.get(httpUrl.host());
					return cookies != null ? cookies : new ArrayList<Cookie>();
				}
			}).build();
			Request request1 = new Request.Builder().url("http://42.247.3.125/jsxsd/xskb/xskb_list.do").build();// 学期理论课表
			httpClient.newCall(request1).enqueue(new Callback() {

				@Override
				public void onResponse(Call arg0, Response arg1) throws IOException {
					// TODO Auto-generated method stub
					String xx = arg1.body().string().toString();
					System.out.println(xx);
				}
				@Override
				public void onFailure(Call arg0, IOException arg1) {
					// TODO Auto-generated method stub
				}
			});
		}
		Log.e("成绩", "xxx");
		httpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
			@Override
			public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
				// TODO Auto-generated method stub
				//将sever的cookie存储到本地
				cookieStore.put(httpUrl.host(), list);
			}
			@Override
			public List<Cookie> loadForRequest(HttpUrl httpUrl) {
				// TODO Auto-generated method stub
				List<Cookie> cookies = cookieStore.get(httpUrl.host());
				//从本地拿取需要的cookie
				return cookies != null ? cookies : new ArrayList<Cookie>();
			}
		}).build();

		Request request = new Request.Builder().url(cjcxstrString).build();// 课程成绩查询
		httpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onResponse(Call arg0, Response response) throws IOException {
				// TODO Auto-generated method stub
				String str1 = response.body().string().toString();
				// Log.d("课程成绩查询页面", str1);
				httpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
					@Override
					public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
						// TODO Auto-generated method stub
						cookieStore.put(httpUrl.host(), list);
					}
					@Override
					public List<Cookie> loadForRequest(HttpUrl httpUrl) {
						// TODO Auto-generated method stub
						List<Cookie> cookies = cookieStore.get(httpUrl.host());
						//
						return cookies != null ? cookies : new ArrayList<Cookie>();
					}
				}).build();
				Request request = new Request.Builder().url(cjliststr).build();
				String strcjli = httpClient.newCall(request).execute().body().string().toString();
				Log.e("全部成绩列表", strcjli);
				// System.out.println(strcjli);
				Log.e("get", "2");
				String regEx1 = "<td align=\"left\">(.*?)</td>";

				Pattern p1 = Pattern.compile(regEx1, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
				String regEx2 = "700,500\\)\">(.*?)</a> -->";
				Pattern p2 = Pattern.compile(regEx2, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
				Matcher m1 = p1.matcher(strcjli);
				Matcher m2 = p2.matcher(strcjli);
				Intent intent = new Intent(sixListActivity.this, ListVuewActivity.class);
				String kc = null;
				String kcmc = null;
				String score = null;
				int i = 1;
				while (m1.find()) {
					// Log.e("dsfddsf", m1.group(1));
					kcmc = m1.group(1);
					if (i % 2 == 0) {
						if (m2.find()) {
							// Log.e("dsfddsf", m2.group(1));
							score = m2.group().substring(10, 12).replaceAll("<", "");
							// 添加 课程编号、课程名称、成绩到listview
							mylist.add(new ScoreMode(kcmc, kc, score));
							Log.e("课程名称", kcmc);
							Log.e("课程编号", kc);
							Log.e("分数", score);
						}
					} else {
						kc = m1.group(1);
					}
					i++;
				}
				startActivity(intent);
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
			}
		});

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		edusrname = (EditText) findViewById(R.id.eduser);
		edpassword = (EditText) findViewById(R.id.edpassword);

		edusrname.setText("1610503446");
		edpassword.setText("zhao19960725");
		// Toast.makeText(sixListActivity.this, edusrname.getText().length(),
		// Toast.LENGTH_SHORT).show();
		edcode = (EditText) findViewById(R.id.edcode);
		/*if (edcode.getText().toString()=="") {
			Toast.makeText(sixListActivity.this, "验证码不能为空！", Toast.LENGTH_SHORT).show();
		}*/
		imvcode = (ImageView) findViewById(R.id.imageView1);
		imvcode.setAdjustViewBounds(true);
		btnlog = (Button) findViewById(R.id.button1);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case 1:
					byte[] picbytes = (byte[]) msg.obj;
					Bitmap picBitmap = BitmapFactory.decodeByteArray(picbytes, 0, picbytes.length);
					imvcode.setImageBitmap(picBitmap);
					break;
				case 2:
					getcj();
					break;
				case 3:
					Toast.makeText(sixListActivity.this, "验证码错误，已重新加载！", Toast.LENGTH_SHORT).show();
					edcode.setText("");
					byte[] r_picbytes = (byte[]) msg.obj;
					Bitmap r_picBitmap = BitmapFactory.decodeByteArray(r_picbytes, 0, r_picbytes.length);
					imvcode.setImageBitmap(r_picBitmap);
					break;
				default:
					break;
				}
			}
		};
		httpClient = new OkHttpClient();
		geturlandCode();
		btnlog.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onpostpwd();
			}
		});
	}

}
